from django.db.models import F
from django.forms import model_to_dict
from django.http import HttpResponse
from django.db import transaction
from rest_framework.views import APIView
from UserProfile import models
from rest_framework.response import Response
from UserProfile.serializers import UserSerializer,CollectionsSerializer
from Blog.util import DataFailed,LimitPagination
import json
from Blog.models import Blog,Collection
from Blog.serializers import BlogSerializer
from Blog.blog import getType



class UserInfo(APIView):
    ##个人信息查看
    def get(self, request, *args, **kwargs):
        user_id = request.user[0]['id']
        #查询
        try:
            user = models.User.objects.filter(id=user_id,is_active=1).values('username','nickname', 'realname','tel','avatar','gender', 'email','email_status','birth','introduction')
        except:
            raise DataFailed({"status": "201", "msg": "查询失败"})
        ser = UserSerializer(user, many=True)
        print(ser.data)
        response = {'status': "200", 'msg': "查找成功", 'data': ser.data}
        return Response(response)

    def post(self, request, *args, **kwargs):
        try:
            data = json.loads(request.body)
        except:
            raise DataFailed({"status": "201", "msg": "数据结构错误"})

        user_id = request.user[0]['id']
        user = getUser(user_id)
        try:
            email = data['email']
            if email != user.email:
                data['email_status'] = 0
                print(0)
        except:
            raise DataFailed({"status": "201", "msg": "数据结构错误"})
        try:
            res = models.User.objects.filter(id=user_id).update(**data)
        except Exception as e:
            raise DataFailed({"status": "202", "msg": "更新失败"})

        response = {'status': "200", 'msg': "更新成功"}
        return Response(response)

#博客
class Bloginfo(APIView):
    #查看
    def get(self, request, *args, **kwargs):
        user_id = request.user[0]['id']
        user = getUser(user_id)
        res = Blog.objects.filter(user=user,status=1).values('id','type', 'cover','user','title','content', 'is_recommend','ctime','view','comments','goods','collections').order_by('-ctime')

        p = LimitPagination()  # 注册分页
        page_user_list = p.paginate_queryset(queryset=res, request=request, view=self)
        ser = BlogSerializer(page_user_list, many=True)  # 可允许多个
        return p.get_paginated_response("200", "获取成功", ser.data)

    #删除
    def delete(self,request, *args, **kwargs):
        id =   request.GET.get('id')
        user_id = request.user[0]['id']
        user = getUser(user_id)
        check = Blog.objects.filter(user=user,id=id).exists()
        if check:
            try:
                Blog.objects.filter(id=id).delete()
            except:
                raise DataFailed({'status': "202", 'msg': "删除失败"})
        else:
            raise DataFailed({'status': "201", 'msg': "没有找到博客"})
        response = {'status': "200", 'msg': "删除成功"}
        return Response(response)

    #修改
    def put(self,request, *args, **kwargs):
        try:
            data = json.loads(request.body)
        except:
            raise DataFailed({"status": "201", "msg": "数据结构错误"})

        user_id = request.user[0]['id']
        user = getUser(user_id)
        try:
            id = data['id']
        except:
            raise DataFailed({"status": "202", "msg": "博客不存在"})
        #检查有无权限
        check = Blog.objects.filter(user=user, id=id).exists()
        if check is False:
            raise DataFailed({"status": "202", "msg": "暂无权限"})
        #替换type
        try:
            type_id = data['type']
            data['type'] = getType(type_id)
        except:
            raise DataFailed({"status": "202", "msg": "类型不为空"})

        #修改操作
        try:
            res = Blog.objects.filter(id=id).update(**data)
        except Exception as e:
            raise DataFailed({"status": "203", "msg": "更新失败"})

        response = {'status': "200", 'msg': "更新成功"}
        return Response(response)


#收藏管理

class Collections(APIView):
    #收藏博客
    #查看
    def get(self, request, *args, **kwargs):
        user_id = request.user[0]['id']
        user = getUser(user_id)
        # Project.objects.get(name='Ops').uhost_set.values('name')nickname=F('coreuserwxprofile__nickname')
        # res = Collection.objects.filter(user=user).values('blog__id','blog__type', 'blog__cover','blog__user','blog__title','blog__content', 'blog__is_recommend','blog__ctime','blog__view','blog__comments','blog__goods','blog__collections','blog__ctime').annotate(id=F('blog__id'),type=F('blog__type'),user=F('blog__user'),cover=F('blog__cover'),title=F('blog__title'),content=F('blog__content'),is_recommend=F('blog__is_recommend'),view=F('blog__view'),comments=F('blog__comments'),goods=F('blog__goods'),collections=F('blog__collections'),ctime=F('blog__ctime')).order_by('-ctime')
        res = Collection.objects.filter(user=user).values('id','ctime','blog__id','blog__type', 'blog__cover','blog__user','blog__title','blog__content', 'blog__is_recommend','blog__ctime','blog__view','blog__comments','blog__goods','blog__collections','blog__ctime').order_by('-ctime')
        print(res)
        p = LimitPagination()  # 注册分页
        page_user_list = p.paginate_queryset(queryset=res, request=request, view=self)
        ser = CollectionsSerializer(page_user_list, many=True)  # 可允许多个
        return p.get_paginated_response("200", "获取成功", ser.data)


    #删除
    def delete(self,request, *args, **kwargs):
        id =  request.GET.get('id')
        user_id = request.user[0]['id']
        user = getUser(user_id)
        check = Collection.objects.filter(user=user,id=id).exists()
        if check:
            result = Collection.objects.get(id=id)
            blog_id = result.blog_id
            blog = getBlog(blog_id)
            try:
                with transaction.atomic():
                    Collection.objects.filter(id=id).delete()
                    blog.collections = F('collections') - 1
                    blog.save()
            except:
                raise DataFailed({'status': "202", 'msg': "删除失败"})
        else:
            raise DataFailed({'status': "201", 'msg': "没有找到记录"})
        response = {'status': "200", 'msg': "删除成功"}
        return Response(response)


#获取实例
def getUser(id):
    try:
        ret = models.User.objects.get(id=id)
    except Exception as e:
        raise DataFailed({"status": "202", "msg": "用户不存在"})
    return ret

def getBlog(id):
    try:
        ret = Blog.objects.get(id=id)
    except:
        raise DataFailed({"status": "202", "msg": "博客不存在"})
    return ret

